package com.woniuxy.qiantai.controller;


import com.woniuxy.qiantai.entity.Address;
import com.woniuxy.qiantai.entity.User;
import com.woniuxy.qiantai.service.AddressService;
import com.woniuxy.qiantai.service.UserService;
import com.woniuxy.qiantai.utils.CookieUtils;
import com.woniuxy.qiantai.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author firstGroup
 * @since 2023-02-22 09:45:58
 */
@RestController
@RequestMapping("/address")
public class AddressController {
    @RequestMapping("add")
    public String add(){
        return "search";
    }

    @Autowired
    private AddressService addressService;
    @Autowired
    private UserService userService;

    /**
     * 查询出此用户的所有收货地址
     * @param request HttpServletRequest对象
     * @return 操作完成返回"ok"
     */
    @RequestMapping("selectAllAddress")
    public List<Address> selectAllAddress(HttpServletRequest request){
        User user = getCurentUser(request);
        /*User user=new User();
        user.setId(1);*/
        List<Address> addressList= addressService.selectAllAddress(user.getId());
        return  addressList;
    }
    /**
     * 用户新增地址
     * @param request HttpServletRequest对象
     * @param area 省市区 字符串数组
     * @param detailAddress 详细地址
     * @param receiveName 收件人姓名
     * @param tel 收件人联系电话
     * @return  操作完成返回"ok"
     */
    @RequestMapping("addAddress")
    public String addAddress(HttpServletRequest request, @RequestParam(value = "area[]") String[] area,String detailAddress,String receiveName,String tel ){
         User user = getCurentUser(request);
    /*    User user=new User();
        user.setId(1);*/
        System.out.println(Arrays.toString(area));
        System.out.println(detailAddress);
        System.out.println(receiveName);
        System.out.println(tel);
        addressService.insertAddress(user.getId(),area,detailAddress,receiveName,tel);
        return  "ok";
    }
    private User getCurentUser(HttpServletRequest request) {
        //通过请求拿到cookie中的token 再从token中获取用户名 再根据用户名查找出user对象
        String token = CookieUtils.getUserTokenFromCookie(request);
        String name = JwtUtils.getAccount(token);
        User userByUserName = userService.getUserByUserName(name);
        return userByUserName;
    }
}

